﻿using AutoMapper;
using SIG.InputModel.Front.Identity;
using SIG.Model.ViewModel.Identity;
using SIG.Service.Identity;
using SIG.ViewModel;
using SIG.ViewModel.Front.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace SIG.WebMVC.Controllers.API
{
    public class UserController : BaseApiController
    {

        IUserService _userService;
        IMapper _mapper;
        public UserController(IUserService UserService, IMapper mapper)
        {
            _userService = UserService;
            _mapper = mapper;
        }

        [HttpPost]
        [Route("api/user/register")]
        public async Task<HttpResponseMessage> Register(RegisterIMForAPI model)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Request.CreateResponse(HttpStatusCode.OK, AR);
            }

            try
            {
                var result = await _userService.RegisterForAPI(model);

                if (result == 1)
                {
                    AR.Setfailure("邮箱已被使用");
                    return Request.CreateResponse(HttpStatusCode.OK,AR );
                }


                if (result == 2)
                {
                    AR.Setfailure("用户名已存在");                   
                    return Request.CreateResponse(HttpStatusCode.OK, AR);
                }

                AR.SetSuccess("注册成功！");
                return Request.CreateResponse(HttpStatusCode.OK, AR);

            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
            }

        }

        [HttpPost]
        [Route("api/user/login")]        

        public async Task<HttpResponseMessage> Login(LoginIMForAPI model)
        {

            if (ModelState.IsValid)
            {

                var user = await _userService.SignInForAPI(model.Username, model.Password);
                if (user != null)
                {
                    var roles = user.Roles.Select(m => m.RoleName).ToArray();

                    user.LastActivityDate = DateTime.Now;
                    _userService.Update(user);

                    //设置cookies
                    _userService.SetUserCookies(true, user);
                    var userVM = _mapper.Map<UserVM>(user);

                    return Request.CreateResponse(HttpStatusCode.OK, userVM);
                }else
                {
                    var message = "无效的用户名或密码！";
                    HttpError err = new HttpError(message);
                    return Request.CreateResponse(HttpStatusCode.BadRequest, err);
                }
            }else 
            {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            } 

        }

     
    }
}
